package com.cpic.blood.admin.controller;

import com.alibaba.fastjson.JSONObject;
import com.cpic.blood.core.common.R;
import com.cpic.blood.core.dto.LoginRequest;
import com.cpic.blood.core.service.impl.JwtUserDetailsService;
import com.cpic.blood.core.utils.JwtTokenUtil;
import com.cpic.blood.core.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class LoginController {

    @Resource
    private RedisUtil redisUtil;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Resource
    private JwtUserDetailsService jwtUserDetailsService;

    @PostMapping("/auth")
    public R auth(@RequestBody LoginRequest loginRequest) {
        // 进行认证
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword())
        );

        // 生成JWT
        UserDetails userDetails = jwtUserDetailsService.loadUserByUsername(loginRequest.getUsername());
        String token = jwtTokenUtil.generateToken(userDetails);

        // 返回JWT给客户端
        return R.success(token);
    }

    @PostMapping("/login")
    public R login(@RequestBody LoginRequest loginRequest) {
        // 生成JWT
        UserDetails userDetails = jwtUserDetailsService.loadUserByUsername(loginRequest.getUsername());
        String token = jwtTokenUtil.generateToken(userDetails);

        if(!loginRequest.getPassword().equalsIgnoreCase(userDetails.getPassword())){
            return R.error("用户密码不正确，请重新输入");
        }

        redisUtil.setEx(token, JSONObject.toJSONString(userDetails),30, TimeUnit.MINUTES);

        // 返回JWT给客户端
        return R.success(token);
    }

    @PostMapping("/logout")
    public R logout(@RequestBody LoginRequest logoutRequest, HttpServletRequest request) {
        String token = request.getHeader("token");
        // 从 Redis 中删除 token
        redisUtil.delete(token);

        // 返回成功消息给客户端
        return R.success("Logout successful");
    }

}